package com.naqiang.electronicdictionary.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.naqiang.electronicdictionary.R;
import com.naqiang.electronicdictionary.adapter.UnKnownWordAdapter;
import com.naqiang.electronicdictionary.data.Constans;
import com.naqiang.electronicdictionary.data.DBOperationImpl;
import com.naqiang.electronicdictionary.entity.MyUnKnowWord;
import com.naqiang.electronicdictionary.entity.UnKnowWord;
import com.naqiang.electronicdictionary.net.DeleteOnlineNote;
import com.naqiang.electronicdictionary.net.GetOnlineNote;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Author by naqiang, Date on 2019\3\15 0015.
 * PS: Not easy to write code, please indicate.
 * 单词本的Fragment
 */
public class NoteFragment extends BaseFragment implements UnKnownWordAdapter.OnUnknowNoteSignDeletedLIstener {

    private static final String TAG = "NoteFragment";
    private ListView lv_note;
    private DBOperationImpl dbOperation;
    private UnKnownWordAdapter unKnownWordAdapter;
    private List<MyUnKnowWord> list = new ArrayList<>();

    @Override
    protected int setView() {
        return R.layout.fragment_note;
    }

    @Override
    protected void initView(View view) {
        lv_note = view.findViewById(R.id.lv_note);
        unKnownWordAdapter = new UnKnownWordAdapter(list, getActivity());
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        dbOperation = DBOperationImpl.getInstance();
    }

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void setListener() {
        unKnownWordAdapter.setOnUnknowNoteSignDeletedLIstener(NoteFragment.this);
        lv_note.setAdapter(unKnownWordAdapter);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {// 不在最前端界面显示

        } else {// 重新显示到最前端
            refreshListView();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshListView();
    }

    @Override
    public void doWork() {
    }

    @Override
    public void onUnknowSignDeleted(final int position, TextView textView) {

        if (!list.get(position).isOnline) {
            Observable.create(new ObservableOnSubscribe<List<MyUnKnowWord>>() {
                @Override
                public void subscribe(ObservableEmitter<List<MyUnKnowWord>> e) {
                    dbOperation.deleteUnKnowWord(list.get(position).unKnowWord);
                    refreshListView();
                    e.onNext(list);
                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<List<MyUnKnowWord>>() {

                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(List<MyUnKnowWord> unKnowWords) {
                           /* list = unKnowWords;
                            unKnownWordAdapter = new UnKnownWordAdapter(list, getActivity());
                            unKnownWordAdapter.setOnUnknowNoteSignDeletedLIstener(NoteFragment.this);
                            lv_note.setAdapter(unKnownWordAdapter);*/
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            deleteOnlineNote(list.get(position).unKnowWord.id);
        }
    }

    /**
     * 通过重新从数据库取值刷新listView
     */
    private void refreshListView() {
        if(list!=null){
            list.clear();
        }
        Observable.create(new ObservableOnSubscribe<List<MyUnKnowWord>>() {
            @Override
            public void subscribe(ObservableEmitter<List<MyUnKnowWord>> e) {

                List<UnKnowWord> list1 = dbOperation.getAllUnKnowWord();
                for (UnKnowWord unKnowWord : list1) {
                    list.add(new MyUnKnowWord(false, unKnowWord));
                }
                e.onNext(list);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<MyUnKnowWord>>() {

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(List<MyUnKnowWord> unKnowWords) {
                        list = unKnowWords;
                        unKnownWordAdapter = new UnKnownWordAdapter(list, getActivity());
                        unKnownWordAdapter.setOnUnknowNoteSignDeletedLIstener(NoteFragment.this);
                        lv_note.setAdapter(unKnownWordAdapter);
                        getOnlineNote();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 从服务器数据库获取所有生词
     */
    private void getOnlineNote() {
        if (Constans.CURRENT_USER == null | "".equals(Constans.CURRENT_USER)) {
            return;
        }
        //创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constans.ADDRESS_HEAD) // 设置 网络请求 Url
                .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 支持RxJava
                .build();

        // 创建 网络请求接口 的实例
        final GetOnlineNote request = retrofit.create(GetOnlineNote.class);

        // 采用Observable<...>形式 对 网络请求 进行封装
        Observable<List<UnKnowWord>> observable = request.getCall(Constans.CURRENT_USER);

        // 发送网络请求
        observable.subscribeOn(Schedulers.io())               // 在IO线程进行网络请求
                .observeOn(AndroidSchedulers.mainThread())  // 回到主线程 处理请求结果
                .subscribe(new Observer<List<UnKnowWord>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d(TAG, "开始采用subscribe连接");
                    }

                    @Override
                    public void onNext(List<UnKnowWord> result) {
                        // 对返回的数据进行处理
                        for (UnKnowWord unKnowWord : result) {
                            Log.i("kkikkikkk", unKnowWord.toString());
                            list.add(new MyUnKnowWord(true, unKnowWord));
                        }
                        unKnownWordAdapter = new UnKnownWordAdapter(list, getActivity());
                        unKnownWordAdapter.setOnUnknowNoteSignDeletedLIstener(NoteFragment.this);
                        lv_note.setAdapter(unKnownWordAdapter);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "请求失败");
                    }

                    @Override
                    public void onComplete() {
                        Log.d(TAG, "请求成功");
                    }
                });
    }

    /**
     * 从服务器数据库删除生词
     */
    private void deleteOnlineNote(int id) {
        if (Constans.CURRENT_USER == null | "".equals(Constans.CURRENT_USER)) {
            return;
        }
        //创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constans.ADDRESS_HEAD) // 设置 网络请求 Url
                .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 支持RxJava
                .build();

        // 创建 网络请求接口 的实例
        final DeleteOnlineNote request = retrofit.create(DeleteOnlineNote.class);

        // 采用Observable<...>形式 对 网络请求 进行封装
        Observable<String> observable = request.deleteNote(id);

        // 发送网络请求
        observable.subscribeOn(Schedulers.io())               // 在IO线程进行网络请求
                .observeOn(AndroidSchedulers.mainThread())  // 回到主线程 处理请求结果
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d(TAG, "开始采用subscribe连接");
                    }

                    @Override
                    public void onNext(String result) {
                        // 对返回的数据进行处理
                        refreshListView();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "请求失败");
                    }

                    @Override
                    public void onComplete() {
                        Log.d(TAG, "请求成功");
                    }
                });
    }
}
